package com.br.pfm.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

@Slf4j
public class ApplicationInitializer implements WebApplicationInitializer {
	
	final static String IGNORE_PATTERN = "/^+\\.(?:jpg|gif|png|css|js|jpeg|mp4|mov|jsp)$";
	
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		//load application context
		final AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
		rootContext.register(ApplicationContext.class);
		rootContext.setDisplayName("PFM");
		
		//char encoding filter
		registerCharacterEncodingFilter(servletContext);
		
		//context load listener
		servletContext.addListener(new ContextLoaderListener(rootContext));
		
		//method filter
		servletContext.addFilter("HttpMethodFilter", org.springframework.web.filter.HiddenHttpMethodFilter.class)
			.addMappingForUrlPatterns(null, false, "/*");
		
		//static resource handling using "default" servlet
		servletContext.getServletRegistration("default").addMapping("*.js", "*.css", "*.jpg", "*.gif", "*.png",
                "*.mov", "*.mp4", "*.ttf", "*.otf");
		
		//dispatcher servlet
		final ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
				new DispatcherServlet(rootContext));
		
		System.out.println("PFM initialized.");
		
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping("/");
		
	}
	
	private void registerCharacterEncodingFilter(final ServletContext servletContext) {
		final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
		characterEncodingFilter.setEncoding("UTF-8");
		characterEncodingFilter.setForceEncoding(true);
		final FilterRegistration.Dynamic filter = servletContext.addFilter("characterEncodingFilter",
				characterEncodingFilter);
		filter.addMappingForUrlPatterns(null, false, "/*");
	}

}
